#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <signal.h>


typedef unsigned short  u16;
typedef unsigned int    u32;

struct input_event {
	struct timeval time;
	u16 key_type;
	u16 key;
	u32 key_value;
};

#define EV_KEY			0x01

#define KEY_L			    (0x26)
#define KEY_S			    (0x1F)
#define KEY_ENTER		    (0x1C)
#define KEY_LEFTSHIFT		(0x2A)




static int g_fd;
void signal_handler(int signo)
{
    printf("Receive signal[%d]\n", signo);
    if(signo == SIGIO)
    {
        struct input_event evt;
        if(read(g_fd, &evt, sizeof(struct input_event))  == sizeof(struct input_event))
        {
            printf("key type[0x%x], key[0x%x], key value[%d]\n", evt.key_type, evt.key, evt.key_value);
            printf("The key[0x%x] is released\n", evt.key, !evt.key_value ? "released" : "pressed");

        }
    }
}

int main(int argc,char *argv[])
{
    const char *dev_name = "/dev/event1";
	g_fd = open(dev_name, O_RDWR | O_NONBLOCK);
    if(g_fd < 0)
    {
        printf("Open the device:[%s] failed\n", dev_name);
        return -1;
    }
    //[0]. 注册一个信号处理函数
    signal(SIGIO, signal_handler);
    //[1]. 为了使内核驱动发送的信号能够到达本应用程序，需要将本程序的进程ID告诉内核
    pid_t pid = getpid();
    fcntl(g_fd, F_SETOWN, pid);
    //[2]. 修改文件描述符g_fd的flag,使其可以接收异步信号
    int old_flags = fcntl(g_fd, F_GETFL);
    int new_flags = old_flags | FASYNC;
    fcntl(g_fd, F_SETFL, new_flags);
    
    while(1)
    {
        sleep(100);
    }
	close(g_fd);
	return 0;
}
